package com.sgy.zookeeper_api;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class UpdateNoteData implements Watcher {

    // 允许等待一个线程
    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    private static ZooKeeper zooKeeper;

    /*
        建立会话
     */
    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        /*
        * connectString：连接地址（ip:port）
        * sessionTimeout：会话超时时间
        * watcher：监听器
        * */
        zooKeeper = new ZooKeeper("192.168.201.129:2181", 30000, new UpdateNoteData());
        System.out.println(zooKeeper.getState());

        Thread.sleep(Integer.MAX_VALUE);


    }

    /**
     * 回调方法：处理来自服务器端的watcher通知
     * @param watchedEvent
     */
    @Override
    public void process(WatchedEvent watchedEvent) {
        System.out.println(watchedEvent.getState());
        // SyncConnected
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            // 更新数据节点内容
            try {
                updateNodeSync();
            } catch (KeeperException e) {
                throw new RuntimeException(e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /*
    * 更新数据节点内容
    * */
    private void updateNodeSync() throws KeeperException, InterruptedException {
        /*
            path:路径
            data:要修改的内容 byte[]
            version:为-1，表示对最新版本的数据进⾏修改
        */
        byte[] data = zooKeeper.getData("/zk-persisent", false, null);
        System.out.println("修改前的值：" + new String(data));
        Stat stat = zooKeeper.setData("/zk-persisent", "修改后的持久节点内容".getBytes(), -1);
        byte[] data2 = zooKeeper.getData("/zk-persisent", false, null);
        System.out.println("修改后的值：" + new String(data2));
    }
}
